package app.services.bus.subscibe;

import app.Const;
import app.dtos.IntegralType;
import app.kit.TypeKit;
import app.models.analyze.Loginlog;
import app.models.member.Account;
import app.models.member.IntegralRecord;
import app.models.member.Points;
import app.services.bus.event.UserLoginEvent;
import com.google.common.base.Optional;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.joda.time.DateTime;

/**
 * <p>
 *     用户登录成功的消费事件
 * </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class UserLoginSubscriber {


    public UserLoginSubscriber(EventBus eventBus) {
        eventBus.register(this);
    }


    @Subscribe
    public void handleLogin(UserLoginEvent loginEvent) {


        int integral = 0;

        if (loginEvent.status) {
            if (IntegralRecord.dao.checkToday(loginEvent.loginTime, loginEvent.userId, IntegralType.SIGNIN)) {
                Optional<Points> optional_points = Points.dao.findByCode(Const.POINTS_CODE.SIGN);
                if (optional_points.isPresent()) {
                    final Points points = optional_points.get();
                    if (points.getNumber(Const.FIELD_STATUS).intValue() == 1) {
                        integral = points.getNumber(Const.FIELD_INTEGRAL).intValue();

                        final Account account = Account.dao.findbyMember(loginEvent.userId);
                        final int db_integral = TypeKit.getInt(account, Const.FIELD_INTEGRAL);
                        final int balance =(db_integral < 0) ? integral : db_integral + integral;
                        account.set(Const.FIELD_INTEGRAL, balance);
                        if (account.update()) {
                            IntegralRecord.dao.earning(DateTime.now(), loginEvent.userId, IntegralType.SIGNIN,"每日登录系统奖励",  integral, balance);
                        }
                    }
                }
            }
        }

        // 纪录登录日志
        Loginlog.dao.record(loginEvent.userId, loginEvent.userName, loginEvent.ip, loginEvent.status ? 1 : 0, integral);

    }

}
